<!DOCTYPE html>
<html>
<head>
    <title>PDF Annotation And Drawing Markup Plugin</title>

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/prettify/r298/prettify.min.css">
    <link rel="stylesheet" href="pdfAnnotator.css">
</head>

<body>
    <div class="sidebar">
        <ul class="sidebarList">
            <li class="logoTitle">Fellowmark.</li>
            <li class="sidebarRow" onclick="navigateHome(window.localStorage.getItem('userRole'))">
                <div id="icon"><img src="images/homeLogo.png" width="20" height="20"></div>
                <div id="title">Home</div>
            </li>
            <li class="sidebarRow" onclick="navigateModule(window.localStorage.getItem('userRole'))">
                <div id="icon"><img src="images/moduleLogo.png" width="20" height="20"></div>
                <div id="title">Modules</div>
            </li>
            <li class="sidebarRow" onclick="logoutUser(window.localStorage.getItem('satoken'))">
                <div id="icon"><img src="images/logoutLogo.png" width="20" height="20"></div>
                <div id="title">Logout</div>
            </li>
        </ul>
    </div>
    
    <div class="toolbar">
        <div class="tool">
            <label for="">Brush size</label>
            <input type="number" class="form-control text-right" value="1" id="brush-size" max="50">
        </div>
        
        <div class="tool">
            <label for="">Font size</label>
            <select id="font-size" class="form-control">
                <option value="10">10</option>
                <option value="12">12</option>
                <option value="16" selected>16</option>
                <option value="18">18</option>
                <option value="24">24</option>
                <option value="32">32</option>
                <option value="48">48</option>
                <option value="64">64</option>
                <option value="72">72</option>
                <option value="108">108</option>
            </select>
        </div>
        
        <div class="tool">
            <button class="color-tool active" style="background-color: #212121;"></button>
            <button class="color-tool" style="background-color: red;"></button>
            <button class="color-tool" style="background-color: blue;"></button>
            <button class="color-tool" style="background-color: green;"></button>
            <button class="color-tool" style="background-color: yellow;"></button>
        </div>
        
        <div class="tool">
            <button class="tool-button active"><i class="fa fa-hand-paper-o" title="Free Hand" onclick="enableSelector(event)"></i></button>
        </div>
        <div class="tool">
            <button class="tool-button"><i class="fa fa-pencil" title="Pencil" onclick="enablePencil(event)"></i></button>
        </div>
        <div class="tool">
            <button class="tool-button"><i class="fa fa-font" title="Add Text" onclick="enableAddText(event)"></i></button>
        </div>
        <div class="tool">
            <button class="tool-button"><i class="fa fa-long-arrow-right" title="Add Arrow" onclick="enableAddArrow(event)"></i></button>
        </div>
        <div class="tool">
            <button class="tool-button"><i class="fa fa-square-o" title="Add rectangle" onclick="enableRectangle(event)"></i></button>
        </div>
        <div class="tool">
            <button class="tool-button"><i class="fa fa-picture-o" title="Add an Image" onclick="addImage(event)"></i></button>
        </div>
        <div class="tool">
            <button class="btn btn-danger btn-sm" onclick="deleteSelectedObject(event)"><i class="fa fa-trash"></i></button>
        </div>
        <div class="tool">
            <button class="btn btn-danger btn-sm" onclick="clearPage()">Clear Page</button>
        </div>
        <div class="save-popup" id="save-popup">
            <img src="images/greentick.png">
            <h2>Saved!</h2>
            <p>Annotations saved successfully</p>
            <p>Do you wish to exit?</p>
            <button type="button" style="background-color: red;" onclick="closeSavePopup()">Stay</button>
            <button type="button" onclick=exitReview()>Exit</button>
        </div>
        <div class="tool">
            <button class="btn btn-light btn-sm" style="color: green;" onclick="savePdfData();"><i class="fa fa-save"></i> Save Annotations and Exit</button>
        </div>
    </div>
    
    <div id="pdf-container">
        <div class="gradebar">
            <h5>Grading</h5>
            <form id="gradesForm">
                <grades></grades>
            </form>
            
            <br><br>

            <h5>Comments</h5>
            <form id="commentsForm">
                <comments></comments>
            </form>
            <br>
            <button class="btn btn-light btn-sm" style="background-color: #9FE2BF;" onclick="handleSubmitGradeComment()">Submit Grades and Comments</button>
        
            <div class="success-popup" id="success-popup">
                <img src="images/greentick.png">
                <h2>Submitted!</h2>
                <p>Grades and Comments saved successfully</p>
                <button type="button" onclick="closeSuccessPopup()">OK</button>
            </div>
        </div>
    </div>
    
    <div class="modal fade" id="dataModal" tabindex="-1" role="dialog" aria-labelledby="dataModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                
                <div class="modal-header">
                    <h5 class="modal-title" id="dataModalLabel">PDF annotation JSON data</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">×</span>
                    </button>
                </div>
                
                <div class="modal-body">
                    <pre class="prettyprint lang-json linenums"></pre>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.6.347/pdf.min.js"></script>
    <script>pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.6.347/pdf.worker.min.js';</script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/4.3.0/fabric.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.2.0/jspdf.umd.min.js"></script>
    <script src="https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prettify/r298/prettify.min.js"></script>
    <script src="pdfAnnotator.js" defer></script>
    <script>
        let popup_grades_saved = document.getElementById("success-popup");
        let popup_annots_saved = document.getElementById("save-popup");

        async function handleSubmitGradeComment() {
            for (i = 1; i <= numQuestions; i++) {
                let rubricId;
                let gradeId;
                let maxGrade;
                let minGrade;
                // step 1: get rubric Id from question Id
                await fetch(`http://localhost:8080/rubric/question/${questionIDlist[i-1]}`, {
                    method: 'GET',
                    headers: {
                        "satoken": window.localStorage.getItem("satoken")
                    },
                })
                .then(res => res.json())
                .then(body => {
                    rubricId = body.data['id'];
                    maxGrade = body.data['maxMark'];
                    minGrade = body.data['minMark'];
                });

                // step 2: check if grade input field is empty, above max, or below min
                if (document.getElementById(`gradeQ${i}`).value === "") {
                    alert("Please enter a grade for Q" + i);
                    return;
                }
                if (document.getElementById(`gradeQ${i}`).value > maxGrade) {
                    alert("Maximum grade exceeded for Q" + i);
                    return;
                }
                if (document.getElementById(`gradeQ${i}`).value < minGrade) {
                    alert("Grade falls below minimum for Q" + i);
                    return;
                }

                // step 3: check if grades already existed for (pair Id and rubric Id)
                await fetch(`http://localhost:8080/grade/listGradeByPairId/${pairing_id}/RubricId/${rubricId}`, {
                    method: 'GET',
                    headers: {
                        "satoken": window.localStorage.getItem("satoken")
                    },
                })
                .then(res => res.json())
                .then(body => {
                    if (body.data == null) {
                        // save new grade
                        fetch(`http://localhost:8080/grade/gradeAssignment`, {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                "satoken": window.localStorage.getItem("satoken")
                            },
                            body: JSON.stringify({
                                "pairingId": pairing_id,
                                "grade": document.getElementById(`gradeQ${i}`).value,
                                "comment": document.getElementById(`commentQ${i}`).value,
                                "submissionId": submission_id,
                                "questionId": questionIDlist[i-1]
                            })
                        })
                        .then(response => response.json())
                        .then(msg => { console.log(msg['success']); });
                    }
                    else {
                        // update existing grade
                        gradeId = body.data['gradeId'];
                        fetch(`http://localhost:8080/grade/update`, {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                "satoken": window.localStorage.getItem("satoken")
                            },
                            body: JSON.stringify({
                                "id": gradeId,
                                "pairingId": pairing_id,
                                "rubricId": rubricId,
                                "grade": document.getElementById(`gradeQ${i}`).value,
                                "comment": document.getElementById(`commentQ${i}`).value,
                                "submissionId": submission_id,
                                "questionId": questionIDlist[i-1],
                            })
                        })
                        .then(response => response.json())
                    }
                    // update active = 1 to indicate completed grading
                    fetch(`http://localhost:8080/pairing/update`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            "satoken": window.localStorage.getItem("satoken")
                        },
                        body: JSON.stringify({
                            "id": pairing_id,
                            "assignmentId": assignment_id,
                            "active": 1
                        })
                    })
                    .then(response => response.json())
                });
            }
            // alert success message
            popup_grades_saved.classList.add("open-success-popup");
        }

        function closeSuccessPopup(){
            popup_grades_saved.classList.remove("open-success-popup");
        }

        function closeSavePopup(){
            popup_annots_saved.classList.remove("open-save-popup");
        }

        function exitReview(){
            popup_annots_saved.classList.remove("open-save-popup");
            window.history.replaceState(null, null, window.location.href = `/student/assignment/${assignment_id}/grading`);
            // redirect back to grading tasks page
            window.location.href = `/student/assignment/${assignment_id}/grading`
        }

        function navigateHome(userRole){
            if (userRole === 'stu') {
                window.location.pathname = '/student/home'
            }
            if (userRole === 'staff') {
                window.location.pathname = '/staff/home'
            }
        }
        function navigateModule(userRole){
            if (userRole === 'stu') {
                window.location.pathname = '/student/module'
            }
            if (userRole === 'staff') {
                window.location.pathname = '/staff/module'
            }
        }
        function logoutUser(satoken){
            fetch('http://localhost:8080/user/logout', {
                method: 'GET',
                headers: { "satoken": satoken },
            })
            .then(() => {
                window.history.pushState(null, null, window.location.href = '/login');
                window.history.go(1);
            })
        }
    </script>
</body>
</html>